<template>
  <div>
    <el-upload
      action="#"
      :class="{disable: fileList.length>0&&uplode}"
      :file-list="fileList"
      list-type="picture-card"
      :on-preview="preview"
      :on-change="change"
      :on-remove="onRemove"
      :before-upload="beforeUpload"
      :http-request="request"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览" :visible="isShowDialog" @close="isShowDialog=false">
      <el-row type="flex" justify="center">
        <img :src="previewURL" alt="">
      </el-row>

    </el-dialog>
    <el-progress v-if="isShow" :text-inside="true" :stroke-width="26" :percentage="percent" style="width:146px" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDUnqdARSCfrmQntiGXXGiuvf9NL3VhbFc',
  SecretKey: '8zav0oLbcMr9BwQggPr3ycz5k9H8j35q'
})
export default {
  props: {
    uplode: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fileList: [

      ],
      isShowDialog: false,
      previewURL: '',
      percent: 0,
      isShow: false
    }
  },
  methods: {
    preview(flie) {
      this.previewURL = flie.url
      this.isShowDialog = true
    },
    // 删除的时候把最新的数据给到fileList
    onRemove(file, newFileList) {
      this.fileList = newFileList
    },
    request(parmes) {
      cos.putObject({
        // 储存桶名称
        Bucket: 'maotou-1308577179',
        // 区域名称
        Region: 'ap-nanjing',
        // 文件名
        Key: parmes.file.name,
        StorageClass: 'STANDARD',
        Body: parmes.file, // 上传文件对象
        onProgress: (progressData) => {
          // 上传过程中
          this.isShow = true
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        // 上传结束
        console.log(err || data)
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
        setTimeout(() => {
          this.isShow = false
        }, 1000)
      })
    },

    // 修改的时候把最新的数据给到fileList
    change(file, newFileList) {
      this.fileList = newFileList
    },
    // 上传的校验
    beforeUpload(file) {
      const max = 2 * 1024 * 1024
      if (file.size > max) {
        this.$message.warning('图片大小不能超过2M')
        return false
      }
      const whiteList = ['image/jpeg', 'image/png']
      // 判断上传的文件后缀是不是包含在whiteList里面，如果不是就false
      if (!whiteList.includes(file.type)) {
        this.$message.warning('暂时只支持 jpeg / png 格式')
        this.fileList[0].status = 'success'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.disable{
  ::v-deep .el-upload--picture-card{
    display: none;
  }
}

</style>
<style lang="scss">
img{
  object-fit: cover;
}

</style>
